using GameFramework.Battle.Core;
using UnityEngine;
using Yoozoo.Libs;

namespace Gameplay.PVE.TurnBase
{
    public class GravityComponent : IComponent,ITransmit
    {
        //刚体组件
        public static float gravity = 10f;
        void IClass.OnReset()
        {

        }
        private BattleUnit unit;
        void IComponent.OnInitialize(BattleUnit unit)
        {
            this.unit = unit;
        }

        void IComponent.OnUpdate()
        {
            bool isFallingDown = true;
            if (unit.Data.position.y + unit.Data.velocity.y * Time.deltaTime <= 0)//表示这一帧就要接触地面了
            {
                //检查是否需要反弹
                float reboundSpeed = unit.Data.velocity.y / -3f;

                if (reboundSpeed <= 0.5f)
                {
                    unit.Data.velocity.y = 0;
                    isFallingDown = false;
                }
                else
                {
                    unit.Data.velocity.y = reboundSpeed;
                }
            }
            
            if (isFallingDown)
            {
                unit.Data.velocity -= new Vector3(0,gravity * Time.deltaTime,0);
            }
            else
            {
                float friction = 3 * Time.deltaTime;
                Vector3 accelerate = unit.Data.velocity.normalized * friction;
                if (unit.Data.velocity.sqrMagnitude <= friction * friction)
                {
                    unit.Data.velocity = Vector3.zero;
                }
                else
                {
                    unit.Data.velocity -= accelerate;
                }
            }
        }

        void IComponent.OnBirth()
        {
            
        }
        
        void IComponent.OnDead()
        {
            
        }
        
        void ITransmit.OnTransmit(ETransmitType type, BaseTransmitArg arg)
        {
            
        }
    }
}